from invidious import *
import requests
import sys

from plugins.core.plugin import Plugin
from plugins.core.pluginvideo import PluginVideo
from plugins.core.pluginplaylist import PluginPlaylist

sys.path.append("..")
from src.vobjects.item import Item
from src.vobjects.video import Video
from src.vobjects.channel import Channel
from src.vobjects.playlist import Playlist

from src.history import History

class InvidiousSearch(Plugin):

    def __init__(self, history: History=History()):
        super().__init__(history=history)

        self.name = "Invidious: Search"
        self.is_query_required = True
        self.query_description = """You can input args (separate they with &).
    page: number of page.
    sort_by: [relevance, rating, upload_date, view_count].
    date: [hour, today, week, month, year].
    duration: [short, long].
    type: [video, playlist, channel, all] (default: video).
    feauters: [hd, subtitles, creative_commons, 3d, live, purchased, 4k, 360, location, hdr].
    region: ISO 3166 country code (default: US).

    Example: distrotube&date=hour 
"""

        self.flag = "-is"
        self.full_flag = "--ivsearch"
        self.flag_help = "search videos from invidious by query"
        self.flag_action = ""

    def get_search(self, query: str=""):
        srch = self.invidious.search(query)

        items = []
        for sr in srch:
            if type(sr) == ChannelItem:
                sr.convert(Channel)
                item = sr.to_item()
            elif type(sr) == VideoItem:
                sr.convert(Video)
                sr.url = self.invidious.get_working_mirror() + "/watch?v=" + sr.videoId
                inHistory = sr.in_history(self.history)
                item = sr.to_item(inHistory=inHistory)
            elif type(sr) == PlaylistItem:
                sr.convert(Playlist)
                item = sr.to_item()
            else: continue

            items.append(item)

        return items

    def get_items_by_query(self, query: str=""):
        return self.get_search(query=query)

    def get_items(self):
        return list()

if __name__ == "__main__":
    al = InvidiousSearch()

    items = al.get_items_by_query(query="мастера меча онлайн")
    for item in items:
        print(item.title, item.parent.url)




